(function(document, undefined){
  
var Topic = window.Topic || {};

Topic.Show = (function() {

  var replyForm = '<article class="topic-reply-item"><section class="topic-article"><div class="topic-body"><textarea id="reply-desc" rows="5" cols="50"></textarea><p><button id="reply-button">回覆</button></p></div></section><aside class="topic-userbox">{{uid}}</aside><div class="clear"></div></article>';
  
  return {
    init: function() {
      stLight.options({publisher:'89b82056-ab00-4c43-912b-b628d3b001fc'});
      $('#reply-button').live('click', function(e){
        var $t = $(this).attr('disabled', true);
        var $container = $t.parents('.topic-container');
        var $replyDesc = $('#reply-desc').attr('disabled', true);
        var $loading = $('<img src="/img/s16.gif" alt="" width="16" height="16">').insertAfter($t);
        
        var content = $replyDesc.val().replace(/^\s+|\s+$/, '');
        
        if (content.length == 0) {
          alert('請輸入內容');
          $replyDesc.attr('disabled', false);
          $loading.remove();
          $t.attr('disabled', false);
          return false;
        }
        
        $.ajax({
          url: '/topic/reply',
          dataType: 'json',
          type: 'post',
          data: {
            forum: $('#forum_key').val(),
            topic: $('#topic_id').val(),
            content: content
          },
          success: function(resp) {
            if (resp.ok) {
              $t.parents('.topic-body').html(resp.content).after(['<div class="topic-meta">於 ', resp.time ,' (UTC) 發表</div>'].join(''));
              
              var f = replyForm.replace('{{uid}}', $('#member_name').val());
              $(f).appendTo($container);
            }
          }
        })
        
      });
    }
  }
  
})();

Topic.Show.init();
  
})(document);